package org.springblade.modules.serial;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.SpringUtil;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;

@ChannelHandler.Sharable
@Component
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
		SocketAddress socketAddress = ctx.channel().remoteAddress();
		logger.info("Received from: {}\n",socketAddress);
		logger.info("Received message: {}\n", msg);
        SpringUtil.getBean(BusinessHandler.class).process(msg,socketAddress);
        // 处理业务逻辑
        String response = "Server response: " + msg.toUpperCase();
        ctx.writeAndFlush(response);
//        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("Channel error", cause);
        ctx.close();
    }



}
